package com.example.myapplication.utils;


import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

import com.example.myapplication.WordApp;
import com.example.myapplication.event.TTSWorkingEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Locale;

//单例模式
public class TTSHelper {
    

    private static TTSHelper mInstance;
    private HashMap<String, String> params = new HashMap<>();
    private TextToSpeech  tts;
    private boolean isReady = false;
    private float speed = 1.0f;


    private TTSHelper() {

        tts = new TextToSpeech(WordApp.AppContext,
                new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int status) {
                        if(status == TextToSpeech.SUCCESS) {
                            tts.setSpeechRate(1.0f);
                            tts.setLanguage(Locale.ENGLISH);
                            isReady = status == TextToSpeech.SUCCESS;
                        }
                    }
                });
        tts.setOnUtteranceProgressListener(new UtteranceProgressListener(){
            @Override
            public void onStart(String utteranceId) {

            }

            @Override
            public void onDone(String utteranceId) {
                EventBus.getDefault().post(new TTSWorkingEvent());
            }

            @Override
            public void onError(String utteranceId) {

            }
        });

    }

    public static TTSHelper getInstance() {
        if(mInstance == null) {
            mInstance = new TTSHelper();
        }
        return mInstance;
    }

    public static void prepare() {
        if(mInstance == null) {
            mInstance = new TTSHelper();
        }
    }

    public void speak(String what) {
        if(isReady) {
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,System.currentTimeMillis()+"");
            tts.speak(what, TextToSpeech.QUEUE_FLUSH, params);
        }
    }


    public void stop() {
        if(isReady) {
            tts.stop();
            speak("");
        }
    }

    public String setSpeed(float r) {
        if(isReady) {
            r = Math.min(2.0f,r);
            r = Math.max(0.1f,r);
            tts.setSpeechRate(r);
            speed = r;
        }
        return String.format("%.1f", r); //保留一位小数
    }

    public float getSpeed() {
        return speed;
    }
    

}
